import FormByData, { FormItemType } from "@/components/FormByData/FormByData";
import { User } from "@/typings/api/auth";
import { FormInstance, message, Modal } from "antd";
import { MutableRefObject, useContext, useEffect, useRef } from "react";
import { MainContext } from "@/layout/Main/Main";
import { updateUser } from "@/api/auth";
import { UploadImg } from "../../components/UploadImg";
import { clearAuthData } from "@/utils/request";
import { useNavigate } from "react-router";
import styles from "./Profile.module.scss";

const Profile = () => {
    const preUser: MutableRefObject<User | null> = useRef(null);
    const formItems: FormItemType<User>[] = [
        { label: "头像", name: "avatar", required: true, placeholder: "请上传头像", component: UploadImg },
        { label: "用户名", name: "username", required: true },
        { label: "昵称", name: "nickname" },
        { label: "邮箱", name: "email", required: true },
        { label: "备注", name: "remark", type: "textarea" },
    ];
    const { user, getUserInfo } = useContext(MainContext);
    const formRef = useRef<FormInstance>();
    useEffect(() => {
        formRef.current?.setFieldsValue(user);
        preUser.current = user;
    }, [user]);

    const navigate = useNavigate();
    const submit = async (formData: User) => {
        await updateUser(formData);
        if (formData.username !== preUser.current?.username || formData.email !== preUser.current.email) {
            clearAuthData();
            return Modal.info({
                title: "提醒",
                content: "修改成功，修改用户名/邮箱需要重新登录",
                onOk() {
                    navigate("/login", { replace: true });
                },
            });
        }
        await getUserInfo();
        message.success("更新成功");
    };
    return (
        <div className={`w-full bg-white ${styles.profile}`}>
            <div className="w-[500px] pt-8">
                <FormByData cols={1} formItems={formItems} onSubmit={submit} getFormRef={ref => (formRef.current = ref)} />
            </div>
        </div>
    );
};

export default Profile;
